/**
 * 用户角色关联服务
 * 作者：GodMainCode
 * 创建时间：2024-01-17
 * 修改时间：2024-01-17
 * 修改人：GodMainCode
 */

import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, In } from 'typeorm';
import { User } from './entities/user.entity';
import { Role } from '../role/entities/role.entity';

@Injectable()
export class UserRoleService {
  constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
    @InjectRepository(Role)
    private readonly roleRepository: Repository<Role>,
  ) {}

  /**
   * 为用户分配角色
   * @param userId 用户ID
   * @param roleIds 角色ID列表
   */
  async assignRoles(userId: number, roleIds: number[]): Promise<void> {
    const user = await this.userRepository.findOne({
      where: { id: userId, is_deleted: 0 },
    });

    if (!user) {
      throw new NotFoundException(`ID为${userId}的用户不存在`);
    }

    const roles = await this.roleRepository.findBy({
      id: In(roleIds),
      is_deleted: 0,
    });

    user.roles = roles;
    await this.userRepository.save(user);
  }

  /**
   * 获取用户的角色列表
   * @param userId 用户ID
   * @returns Promise<Role[]> 角色列表
   */
  async getUserRoles(userId: number): Promise<Role[]> {
    const user = await this.userRepository.findOne({
      where: { id: userId, is_deleted: 0 },
      relations: ['roles'],
    });

    if (!user) {
      throw new NotFoundException(`ID为${userId}的用户不存在`);
    }

    return user.roles;
  }

  /**
   * 移除用户的角色
   * @param userId 用户ID
   * @param roleIds 角色ID列表
   */
  async removeRoles(userId: number, roleIds: number[]): Promise<void> {
    const user = await this.userRepository.findOne({
      where: { id: userId, is_deleted: 0 },
      relations: ['roles'],
    });

    if (!user) {
      throw new NotFoundException(`ID为${userId}的用户不存在`);
    }

    user.roles = user.roles.filter(role => !roleIds.includes(role.id));
    await this.userRepository.save(user);
  }
} 